import api from './api';
import { User } from '../types/user';

interface UpdateUserProfileParams {
  firstName?: string;
  lastName?: string;
  email?: string;
  picture?: string;
}

interface ApiResponse<T> {
  success: boolean;
  message?: string;
  data: T;
}

export const userService = {
  /**
   * 更新用户个人资料
   */
  updateUserProfile: async (userId: number, params: UpdateUserProfileParams): Promise<User> => {
    try {
      const response = await api.put<ApiResponse<User>>(`/users/${userId}/profile`, params);
      return response.data.data;
    } catch (error: any) {
      console.error('更新用户资料失败:', error);
      throw new Error(error.response?.data?.message || '更新用户资料失败');
    }
  },

  /**
   * 上传用户头像
   */
  uploadProfileImage: async (userId: number, formData: FormData): Promise<{imageUrl: string}> => {
    try {
      const response = await api.post<ApiResponse<{imageUrl: string}>>(
        `/users/${userId}/profile-image`, 
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      );
      return response.data.data;
    } catch (error: any) {
      console.error('上传头像失败:', error);
      throw new Error(error.response?.data?.message || '上传头像失败');
    }
  },

  /**
   * 获取用户信息
   */
  getUserProfile: async (userId: number): Promise<User> => {
    try {
      const response = await api.get<ApiResponse<User>>(`/users/${userId}/profile`);
      return response.data.data;
    } catch (error: any) {
      console.error('获取用户信息失败:', error);
      throw new Error(error.response?.data?.message || '获取用户信息失败');
    }
  }
};